package cn.zz.veggie.application.service;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.core.types.result.PageResult;
import cn.zz.comm.helper.BizCommHelper;
import cn.zz.comm.types.IdNameObj;
import cn.zz.comm.util.CollectorUtil;
import cn.zz.veggie.application.assembler.ProductAssembler;
import cn.zz.veggie.application.packer.ProductPacker;
import cn.zz.veggie.model.domain.Product;
import cn.zz.veggie.model.query.ProductQuery;
import cn.zz.veggie.persistence.repository.ProductRepository;
import cn.zz.veggie.web.types.dto.mgmt.MgmtProductQueryDto;
import cn.zz.veggie.web.types.dto.mgmt.MgmtProductSaveDto;
import cn.zz.veggie.web.types.vo.mgmt.MgmtProductVo;
import lombok.RequiredArgsConstructor;

/**
 * @author zhongq
 * @since 2024/4/4
 */
@Service
@RequiredArgsConstructor
public class ProductAppService {

	private final ProductRepository productRepository;

	public PageResult<MgmtProductVo> adminFindList(MgmtProductQueryDto dto, PageQuery page) {
		ProductQuery query = ProductAssembler.buildQuery(dto);
		final List<Product> products = productRepository.findByPage(query, page);
		// convert
		return PageResult.of(page, CollectorUtil.bwl(products, ProductPacker::packMgmtVo));
	}

	public void adminSave(MgmtProductSaveDto dto) {
		Product product = ProductAssembler.buildDomain(dto);
		productRepository.save(product);
	}

	public List<IdNameObj<Integer>> adminInputSearch(String keyword) {
		final ProductQuery query = new ProductQuery();
		query.likeName = keyword;
		query.column = ProductQuery.columnIdName;
		List<Product> users = productRepository.findByPage(query, PageQuery.all());
		return CollectorUtil.bwl(users, u -> new IdNameObj<>(u.getId(), u.getName()));
	}

	public void mgmtRemoveProduct(Integer id) {
		final Product product = productRepository.findById(id);
		BizCommHelper.requireNoNull(product, id);
		product.delete();
		productRepository.save(product);
	}
}